package com.ad.pet.app.upgrade;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ad.pet.BuildConfig;
import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.Logger;
import com.ad.pet.R;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.BaseActivity;
import com.qw.download.DownloadDBController;
import com.qw.download.DownloadEntity;
import com.qw.download.DownloadFileUtil;
import com.qw.download.DownloadManager;
import com.qw.download.DownloadWatcher;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;

import javax.inject.Inject;

import rx.functions.Action1;

/**
 * Created by SEELE on 2018/4/9.
 */

public class UpgradeActivity extends BaseActivity {
    private TextView mAppUpdateTitleLabel;
    private TextView mAppUpdateContentLabel;
    private ProgressBar progressBar;
    private TextView mAppUpdateProgressInfoLabel;
    private TextView mAppUpdateLeftBtn;
    private TextView mAppUpdateRightBtn;
    private DownloadEntity e;
    private RxPermissions mRxPermissions;
    private AlertDialog mDialog;
    @Inject
    RxDisposable mRxDisposable;
    private DownloadWatcher watcher = new DownloadWatcher() {
        @Override
        protected void onDataChanged(DownloadEntity downloadEntity) {
            UpgradeActivity.this.e = downloadEntity;
            showButtonText();
            setUpdateInfo(downloadEntity);
        }
    };
    private boolean mIsFinsish;
    private String mUrl;
//    private String msg;

    @Override
    protected void initViews() {
        mIsFinsish = getIntent().getBooleanExtra("isFinish", false);
        mUrl = getIntent().getStringExtra("url");
//        msg = getIntent().getStringExtra("msg");

        mRxPermissions = new RxPermissions(mActivity);
        mDialog = DialogUtil.createDialogNoShow(mActivity, getString(R.string.tips), getString(R.string.refuse_read_storage), false, getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }, getString(R.string.go_set), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mDialog.dismiss();
                        Uri packageURI = Uri.parse("package:" + mActivity.getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        mActivity.startActivity(intent);
                    }
                });
    }




    @Override
    protected void initData() {
        DownloadManager.getInstance(getApplicationContext()).addObserver(watcher);
        mAppUpdateTitleLabel = (TextView) findViewById(R.id.mAppUpdateTitleLabel);
        mAppUpdateContentLabel = (TextView) findViewById(R.id.mAppUpdateContentLabel);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        mAppUpdateProgressInfoLabel = (TextView) findViewById(R.id.mAppUpdateProgressInfoLabel);
        mAppUpdateLeftBtn = (TextView) findViewById(R.id.mAppUpdateLeftBtn);
        mAppUpdateRightBtn = (TextView) findViewById(R.id.mAppUpdateRightBtn);
        hiddenProgressInfo();


        mAppUpdateContentLabel.setText(getString(R.string.find_upgrade_msg));
//        mAppUpdateTitleLabel.setText(getString(R.string.upgrade_tittle));
        e = DownloadManager.getInstance(mActivity).findById(getDownloadId(mUrl));
        if (e == null) {
            e = new DownloadEntity(getDownloadId(mUrl), mUrl);
        }
        showButtonText();
        if (e.state == DownloadEntity.State.idle) {
            hiddenProgressInfo();
        } else {
            int p = (int) (100.0 * e.currentLength / e.contentLength);
            progressBar.setProgress(p);
            mAppUpdateProgressInfoLabel.setText(p + "/" + 100);
            showProgressInfo();
        }
        if (mIsFinsish) {
            mAppUpdateLeftBtn.setVisibility(View.GONE);
        } else {
            mAppUpdateLeftBtn.setText(getString(R.string.cancel));
        }
    }

    private void showButtonText() {
        switch (e.state) {
            case paused:
                mAppUpdateRightBtn.setText(getString(R.string.conntiue));
                break;
            case wait:
                mAppUpdateRightBtn.setText(getString(R.string.waiting));
                break;
            case ing:
            case connect:
                mAppUpdateRightBtn.setText(getString(R.string.downing));
                break;
            case error:
                mAppUpdateRightBtn.setText(getString(R.string.retry));
                break;
            case cancelled:
            case idle:
                mAppUpdateRightBtn.setText(getString(R.string.upgrade));
                break;
            case done:
//                FIXME 用户误删apk包的处理
                File file = new File(DownloadFileUtil.getDownloadPath(e.id));
                if (file.exists()) {
                    mAppUpdateRightBtn.setText(getString(R.string.install));
                } else {
                    DownloadDBController.getInstance(getApplicationContext()).delete(e);
                    e = new DownloadEntity(getDownloadId(mUrl), mUrl);
                }

                break;
            default:
                break;
        }
    }

    private String getDownloadId(String url) {
        int index = url.lastIndexOf("/");
        String after = url.substring(index + 1);
        return after;
    }

    @Override
    protected void initEvents() {
        mAppUpdateLeftBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(RESULT_OK);
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });
        mAppUpdateRightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRxDisposable.add(mRxPermissions.request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (aBoolean) {
                            handlerDownload();
                        } else {
                            mDialog.show();
                        }
                    }
                }));
            }
        });
    }


    private void handlerDownload() {
        switch (e.state) {
            case ing:
            case wait:
            case connect:
                DownloadManager.getInstance(mActivity).pauseDownload(e);
                break;
            case paused:
                DownloadManager.getInstance(mActivity).resumeDownload(e);
                break;
            case error:
                DownloadManager.getInstance(mActivity).resumeDownload(e);
                break;
            case idle:
                showProgressInfo();
                DownloadManager.getInstance(mActivity).addDownload(e);
                break;
            case done:
                String path = DownloadFileUtil.getDownloadPath(e.id);
                installApp(path);
                break;
            default:
                break;
        }
    }

    private void hiddenProgressInfo() {
        progressBar.setVisibility(View.GONE);
        mAppUpdateProgressInfoLabel.setVisibility(View.GONE);
    }


    private void showProgressInfo() {
        progressBar.setVisibility(View.VISIBLE);
        mAppUpdateProgressInfoLabel.setVisibility(View.VISIBLE);
    }

    public void setUpdateInfo(DownloadEntity e) {
        Logger.e("setUpdateInfo state:" + e.state.name());
        switch (e.state) {
            case ing:
                showProgressInfo();
                int p = (int) (100.0 * e.currentLength / e.contentLength);
                progressBar.setProgress(p);
                mAppUpdateProgressInfoLabel.setText(p + "/" + 100);
                break;
            case done:
                showProgressInfo();
                progressBar.setProgress(100);
                mAppUpdateProgressInfoLabel.setText(100 + "/" + 100);
                String path = DownloadFileUtil.getDownloadPath(e.id);
                installApp(path);
                break;
            default:
                break;
        }
    }

    private void installApp(String path) {
        File apkfile = new File(path);
        if (!apkfile.exists()) {
            ToastUtil.getToastUtil().showShort(getString(R.string.unfind_apk));
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(mActivity, BuildConfig.APPLICATION_ID + ".UpgradeFileProvider", apkfile);
            i.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            i.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        startActivity(i);
    }

    @Override
    protected void onDestroy() {
        if (mRxDisposable != null)
        mRxDisposable.clear();
        DownloadManager.getInstance(getApplicationContext()).removeObserver(watcher);
        super.onDestroy();
    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_upgrade;
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void onBackPressed() {
    }
}
